package com.teamclub.app.sservices.systemmanager

import io.ebean.{Ebean, ExpressionList}
import com.fasterxml.jackson.databind.JsonNode
import com.teamclub.app.sforms.AppDomainForm
import com.teamclub.domain.system._
import com.teamclub.util.errors.ErrorCode
import com.teamclub.util.libs.F
import com.teamclub.util.page.Pager
import org.apache.commons.lang3.StringUtils
import org.slf4j.LoggerFactory
import org.springframework.beans.BeanUtils
import org.springframework.stereotype.Service


/**
  * Created by ilkkzm on 17-8-7.
  */

@Service
class AppDomainService {
  val logger = LoggerFactory.getLogger(classOf[AppDomainService])

  def list(form: AppDomainForm): F.Either[JsonNode, ErrorCode] = {
    val where = Ebean.find(classOf[AppDomain]).where()
    expr(where, form)
    F.Either.Left(Pager.genePagerJson(where.query(), form))
  }

  def add(form: AppDomainForm): F.Either[AppDomain, ErrorCode] = {
    var single = new AppDomain
    if(form.id != null) {
      single = Ebean.find(classOf[AppDomain], form.id)
    }
    if(single == null) {
      return F.Either.Right(ErrorCode.ENTITY_NOT_FOUND)
    }
    BeanUtils.copyProperties(form, single)
    if(form.id != null) {
      single.update()
    } else {
      single.save()
    }
    F.Either.Left(single)
  }


  def del(form: AppDomainForm): F.Either[AppDomain, ErrorCode] = {
    val single = Ebean.find(classOf[AppDomain], form.id)
    if(single == null) {
      F.Either.Right(ErrorCode.ENTITY_NOT_FOUND)
    } else {
      single.delete()
      F.Either.Left(single)
    }
  }

  def expr(where: ExpressionList[AppDomain], form: AppDomainForm) = {
    if(form.id != null) {
      where.eq("id", form.id)
    }
    if(StringUtils.isNotBlank(form.appName)) {
      where.like("appName", "%" + form.appName + "%")
    }
    if(StringUtils.isNotBlank(form.appKey)) {
      where.like("appKey", "%" + form.appKey + "%")
    }
  }

}
